#include <bits/stdc++.h>
#ifndef DEBUG
#define debug
#endif
using namespace std;
using i64 = int64_t;

int main() {
  cin.tie(0)->sync_with_stdio(0);
  int n;
  cin >> n;
  vector<int> w(n + 1), a(n + 1);
  for (int i = 1; i <= n; i ++) cin >> w[i];
  for (int i = 1; i <= n; i ++) cin >> a[i];

  const int inf = INT_MIN / 2;
  vector<vector<int>> dp(n + 1, vector<int>(n + 1));
  auto inc = dp, dec = dp;
  for (int l = n; l >= 1; l --) {
    dp[l][l] = w[1];
    inc[l][l] = dec[l][l] = 0;
    for (int r = l + 1; r <= n; r ++) {
      dp[l][r] = inc[l][r] = dec[l][r] =inf;
      for (int k = l; k < r; k ++) {
        dp[l][r] = max(dp[l][r], dp[l][k] + dp[k + 1][r]);
      }
      for (int k = l; k < r; k ++) {
        if (inc[l][k] != inf && a[k] + 1 == a[r]) {
          inc[l][r] = max(inc[l][r], inc[l][k] + dp[k + 1][r - 1]);
        }
        if (dec[l][k] != inf && a[k] - 1 == a[r]) {
          dec[l][r] = max(dec[l][r], dec[l][k] + dp[k + 1][r - 1]);
        }
      }
      for (int k = l; k <= r; k ++) {
        if (inc[l][k] == inf || dec[k][r] == inf) continue;
        int remainLen = a[k] - a[l] + a[k] - a[r] + 1;
        dp[l][r] = max(dp[l][r], w[remainLen] + inc[l][k] + dec[k][r]);
      }
    }
  }
  vector<int> linear(n + 1);
  for (int i = 1; i <= n; i ++) {
    linear[i] = max(0, linear[i - 1]);
    for (int j = 1; j <= i; j ++) {
      linear[i] = max(linear[i], linear[j - 1] + dp[j][i]);
    }
  }
  cout << linear[n] << '\n';
}